package com.yfuxdeer.youchat.client;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yfuxdeer.youchat.pojo.FriendItem;
import com.yfuxdeer.youchat.service.ClientService;
import com.yfuxdeer.youchat.service.FriendService;
import com.yfuxdeer.youchat.activity.ChatActivity;
import com.yfuxdeer.youchat.pojo.Message;
import com.yfuxdeer.youchat.utils.NotificationUtil;
import com.yfuxdeer.youchat.utils.Store;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.util.Date;

public class Client implements Serializable {
    private static final String TAG = Client.class.getSimpleName();
    Socket client;
    private Store store = Store.getInstance();
    private boolean isChat;
    private PrintStream pout;
    private BufferedReader reader;
    private ClientService service;


    public Client(ClientService service) {
        this.service = service;
        try {
            client = new Socket("139.159.226.207", 8503);
            Log.e(TAG, "Client: " + "发起连接");
            pout = new PrintStream(client.getOutputStream());
            //读取客户端的流
            reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            //连接之后向服务器发送一条消息，由服务器保存IP
            send(new Message(store.getCurrentUser().getUsername(), "server", "connected", new Date()));
        } catch (ConnectException e) {
            Log.e(TAG, "网络异常");
            client = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            isChat = true;
            //接受线程
            new ReceiveThread(reader).start();
            if (!isChat) {
                pout.close();
                reader.close();
                client.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void send(Message message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String send = "";
                try {
                    send = new ObjectMapper().writeValueAsString(message);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                if (send == null || "".equals(send)) {
                    return;
                }
                if (pout == null) return;
                pout.println(send);
            }
        }).start();
    }

    public class ReceiveThread extends Thread {

        private static final String TAG = "ReceiveThread";
        private BufferedReader reader;

        public ReceiveThread(BufferedReader reader) {
            this.reader = reader;
        }

        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    Message message = new ObjectMapper().readValue(reader.readLine(), Message.class);
                    String receive = message.getMsg();
                    if (receive == null || "".equals(receive)) {
                        this.interrupt();
                    }
                    NotificationUtil.sendNotification(service.getApplicationContext(), ChatActivity.class, message);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            FriendItem friendItem = null;
                            try {
                                friendItem = FriendService.findFriendById(message.getTo(), message.getFrom());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            Intent intent = new Intent("com.yfuxdeer.youchat.notifyMessageReceiver");
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("message", message);
                            bundle.putSerializable("friendItem", friendItem);
                            intent.putExtras(bundle);
                            service.sendBroadcast(intent);
                        }
                    }).start();

                } catch (Exception e) {
                    Log.e(TAG, "网络异常");
                    e.printStackTrace();
                    this.interrupt();
                }
            }
        }
    }
}